<?php

namespace App\Services\Talking;

use App\Events\TaskEvent;
use App\Models\Group\Group;
use App\Models\Group\GroupMembers;
use App\Models\Group\ChatGroupMessage;
use App\Models\Member\Member;
use App\Models\Member\Friend;
use App\Models\School\School;
use App\Services\Easemob\Groups;
use App\Services\Member\LikeService;
use App\Services\Easemob\UserAuth as EasemobUserAuth;
use App\Services\Com\UtilService;
use App\Services\Group\GroupService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class TalkingService
{

    /**
     * 群存在唯一判断 
     * @param group_id 群id
     * @param member_uuid 某人
     * @return true false
     * */
    public static function groupUnique(string $service_type = '', string $service_uuid = '' , string $member_uuid = '')
    {
        $isCreated = null;
        try {
            $isCreated = Group::query()
                        // ->with('memberInGroup')
                        ->where('service_type', $service_type)
                        ->where('service_uuid', $service_uuid)
                        ->first();
            
            if (!empty($isCreated)) {
                $isCreated['is_created'] = 1;
                $member_in_group = GroupMembers::where('member_uuid', '=', $member_uuid)
                            ->where('group_id', '=', $isCreated->group_id)->first();
                $isCreated['current_member_in_group'] = $member_in_group;

            }
        }catch (\Exception $e){
            Log::alert($e->getMessage());
        }

        return $isCreated;
    }

    /**
     * 批量修改环信群信息
     * */
    public static function modImGroup()
    {
        $res = null;
        try {
            $res_obj = Group::get();
            foreach ($res_obj as $key => $value) {
                // if($value['group_id'] != 198283934892034){
                //     continue;
                // }
                $im_param = null;
                $im_param['group_id']       = $value['group_id'];
                $im_param['group_name']     = $value['name'];
                $im_param['group_name']     = str_replace('/','-',$im_param['group_name']);
                $im_param['group_name']     = str_replace(' ','-',$im_param['group_name']);
                $im_param['maxusers']       = env('GROUP_MAX_USER');
                
                $param['group_id'] = $value['group_id'];
                $im_res = Groups::getGroup($param);
                if(isset($im_res['error']) && !empty($im_res['error'])){
                    continue;
                }
                $result = Group::where('group_id', $value['group_id'])->first();
                $result->maxusers  = env('GROUP_MAX_USER');
                //更新本地
                $groupResult = $result->save();
                if (!$groupResult) {
                    Log::alert('保存失败'.var_export($result, true));
                }
                //更新环信
                $result2 = Groups::updateGroup($im_param);
                if (!empty($result2['code'])) {
                    Log::error($result2);
                }else{
                    Log::info(var_export($result2, true));
                }
            }
            
        }catch (\Exception $e){
            Log::alert('EEEEEE'.$e->getMessage());
        }
;
    }

    /**
     * @param group_id 群id
     * @param member_uuid 某人
     * 返回某人在 群的角色
     * @return int 1群主，2管理员，3一般成员 -1不在群里
     * */
    public static function memberInGroupType(string $group_id = '', string $member_uuid = '')
    {
        $res = null;
        try {
            $res_obj = GroupMembers::where('group_id','=',$group_id)
                ->where('member_uuid', '=', $member_uuid)
                ->first();
            if(!empty($res_obj)){
                $res = $res_obj->toArray();
            }
        }catch (\Exception $e){
            Log::alert($e->getMessage());
        }

        return $res['type'] ?? -1;
    }

    /**
     * @param   $talking uuid
     * 返回talking 详细
     * @return array
     * */
    public static function talkingDetail(string $uuid = '', string $member_uuid = '')
    {

        $res = null;
        try {
            //群组用户头像经另外取
            $talking_res = Group::withCount([
                'groupMembers'=>function($query){
                    $query->join('members', 'members.uuid', '=', 'group_members.member_uuid');
                }
            ])
                ->with([
                    'createUser'=>function($query){
                        $query->select(['avatar_url','uuid', 'nickname']);
                    }
                ])
                ->where('uuid', '=', $uuid)
                ->first();


            if(!empty($talking_res)){
                $talking_res['create_user'] = $talking_res->createUser->toArray();
                //取环信用户状态
                $uuids[] = $talking_res['member_uuid'];
                $online_arr = EasemobUserAuth::getUsersStatusIm($uuids);

                // foreach ($list as $key_l => $value_l) {

                //取三个头像
                $avatar = null;
                $member_list = Member::where('group_id', '=', $talking_res['group_id'])
                    ->join('group_members', 'members.uuid', '=', 'group_members.member_uuid')
                    ->select('members.avatar_url', 'members.uuid', 'group_members.type as member_in_group_type')
                    ->orderByRaw("group_members.member_uuid = '".$member_uuid. "' DESC, group_members.id ASC ")
                    ->limit(3)->get();
                $member_in_group_type = -1;
                //头像合成数组
                foreach ($member_list as $m_key => $m_value) {
                    if(!empty($m_value['avatar_url'])){
                        $avatar[] = $m_value['avatar_url'];
                    }
                    if($m_value['uuid'] == $member_uuid){
                        $member_in_group_type = $m_value['member_in_group_type'];
                    }
                }
                $group_members_count = 0;
                if($talking_res['group_members_count'] > 0){
                    $group_members_count = $talking_res['group_members_count'].'+';
                }

                $res = [

                    'id'=>$talking_res['id'],//talking id
                    'uuid'=>$talking_res['uuid'],//talking uuid
                    'group_id'=>$talking_res['group_id'],//talking 环信 id
                    'owner_uuid'=>$talking_res['owner_uuid'],//talking 环信 owner_uuid
                    'title'=>$talking_res['name'],//标题
                    'username'=>$talking_res['create_user']['nickname'] ?? null,//创建者用户名
                    'member_uuid'=>$talking_res['create_user']['uuid'] ?? null,//创建者uuid
                    'avatar'=>$talking_res['create_user']['avatar_url'] ?? null,//发起者 头像
                    'member_in_group_type'=>$member_in_group_type,//群创建者 type 是1
                    'user_list'=> //用户列表
                        [   'avatar'=>$avatar, //参与用户头像
                            'sum'=>$group_members_count,//参与用户数
                        ],
                    'online'=>$online_arr[$talking_res['member_uuid']] ?? 0,//1在线0不在线
                    'has_like'=>LikeService::hasLike($member_uuid, 7, $talking_res['uuid']),//1是已经点like 0是未点like
                    'sum_like'=>LikeService::sumLike(7, $talking_res['uuid']),//点赞总量
                    'created_at'=>$talking_res['created_at'],//创建时间
                    'service_type'=>$talking_res['service_type'] ?? null,//
                    'service_uuid'=>$talking_res['service_uuid'] ?? null,//

                ];
                // }
            }
        }catch (\Exception $e){
            Log::alert($e->getMessage());
        }

        return $res;
    }

    /**
     * 
     * Talking名称、 在线人数/总人数 、当日新增消息数、   群成员列表（需要区分是否在线）、创建时间、解散群（涉及到违规才会后台管理人员解散）
     * 
     * @param   $page 第几页
     * @param   $member_uuid 用户uuid，查此人状态，头注，在线等
     * @param   $limit 返回条数
     * @param   $position 显示位置    feeds:信息流, 
     *                              hub_top:talking置顶, 
     *                              hub_list:talking列表, 
     *                              school_feeds:学校 我和我的校友加入的
     *                              member_feeds:我的圈子 我的好友的,我的,且屏蔽学校talking
     *                              admin:管理后台
     *                              my_create:我创建的
     *                              discovery:发现固定4条
     * @param   $type 类型
     * @param   $school_uuid  学校talking
     * @param   $query 更多参数: return_page 返回分页数据
     * 返回talking
     * @return array
     * */
    public static function talkingList(int $page = 1, string $member_uuid = '', int $limit = 6, 
        string $position = '', int $type = 0, string $school_uuid = '', array $query = [])
    {

        // $cache_key = config('cache.key_list.talking_list').md5($page.$member_uuid.$limit.$position.$type.$school_uuid);
        // $cache_data = Cache::get($cache_key);
        // if(!empty($cache_data)){
        //     return $cache_data;
        // }

        $data_page = $page; //1,2,0
        $list_res = null;
        $res_page = null;

        $model = Group::withCount([
                        'groupMembers'=>function($query){
                            $query->join('members', 'members.uuid', '=', 'group_members.member_uuid');
                        }
                    ])
                ->with([
                        'createUser'=>function($query){
                            $query->select(['avatar_url','uuid', 'nickname']);
                        }
                    ])
                ;

        if($type != 0){
            $model->where('type', '=', $type);
        }

        //过滤学校的
        $model->where('service_type', '<>', 'school'); 
        isset($query['keywords']) && !empty($query['keywords']) && $model->where('name', 'like', "%{$query['keywords']}%");

        if($position == 'member_feeds' ){ //我的圈子 我的好友的,我的,且屏蔽学校talking
            $model = $model->orderBy('id', 'desc');
            //查我的好友uuid
            $friend_res = Friend::where('member_uuid', $query['show_member_uuid'])->get()->toArray();
            $all_friend_member_uuid = array_column($friend_res, 'friend_member_uuid');
            if(isset($query['show_member_uuid'])){
                $all_friend_member_uuid[] = $query['show_member_uuid'];
            }
            
            $group_members =  GroupMembers::whereIn('member_uuid', $all_friend_member_uuid)->groupBy('group_id')->get()->toArray();
            $group_id_arr = array_column($group_members,'group_id');
            
            if(isset($query['return_page'])){
                //查好友在的群 in 优化
                $model->whereIn('group_id', $group_id_arr);
                $list = $model->paginate($limit);
                $res_page = $list->toArray();
                unset($res_page['data']);
            }else{
                //打乱随机取取N条
                shuffle($group_id_arr);
                $group_id_arr_rand = array_slice($group_id_arr, 0, $limit);
                $model->whereIn('group_id', $group_id_arr_rand);
                $list = $model->forPage($page, $limit)->get();
            }
        }elseif($position == 'school_feeds' ){//学校 我和我的校友加入的
            $model = $model->orderBy('id', 'desc');
            //查我的校友uuid
            $sc_res = Member::where('school_uuid', $school_uuid)->get()->toArray();
            $all_sc_member_uuid = array_column($sc_res, 'uuid');
            
            //查好友在的群 in 优化
            $group_members =  GroupMembers::whereIn('member_uuid', $all_sc_member_uuid)->groupBy('group_id')->get()->toArray();
            $group_id_arr = array_column($group_members,'group_id');

            if(isset($query['return_page'])){
                //查好友在的群 in 优化
                $model->whereIn('group_id', $group_id_arr);
                $list = $model->paginate($limit);
                $res_page = $list->toArray();
                unset($res_page['data']);
            }else{
                //打乱随机取取N条
                shuffle($group_id_arr);
                $group_id_arr_rand = array_slice($group_id_arr, 0, $limit);
                $model->whereIn('group_id', $group_id_arr_rand);
                $list = $model->forPage($page, $limit)->get();
            }
        }elseif($position == 'admin' ){//管理后台
            $model = $model->orderBy('id', 'desc');
            $list = $model->forPage($page, $limit)->get();
        }elseif($position == 'hot' ){//全域信息热门
            $model = $model->orderBy('id', 'desc');
            $model->where('is_recommend', '=', 2);
            $list = $model->forPage(1, 6)->get();
        }elseif($position == 'feeds' ){//全域信息流处
            $model = $model->orderBy('id', 'desc');
            $list = $model->forPage($page, $limit)->get();
        }elseif($position == 'hub_top') {//全域列表置顶
            $model = $model->orderBy('id', 'desc');
            $model->where('is_top', '=', '1');
            $list = $model->limit($limit)->get();
        }elseif($position == 'hub_list'){//全域列表
            $model = $model->orderBy('id', 'desc');
            $model->where('is_top', '<>', '1');
            $list = $model->paginate($limit);
            $res_page = $list->toArray();
            unset($res_page['data']);
        }elseif($position == 'my_create'){//我创建的
            $model = $model->orderBy('id', 'desc');
            $model->where('member_uuid', '=', $query['show_member_uuid']);
            $list = $model->forPage($page, $limit)->get();
        }elseif($position == 'discovery') {//店铺发现
            $model = $model->orderBy('is_top', 'desc');
            $model = $model->orderBy('id', 'desc');
            $list = $model->limit($limit)->get();
        }else{
            $model = $model->orderBy('id', 'desc');
            $list = $model->paginate($limit);
            $res_page = $list->toArray();
            unset($res_page['data']);
        }

        if(!empty($list)){

            //批量取环信用户状态
            $uuids = null;
            foreach ($list as $key_l => $value_l) {
                $value = $value_l->toArray();
                $uuids[] = $value['member_uuid'];
            }
            if(!empty($uuids)){
                $online_arr = EasemobUserAuth::getUsersStatusIm($uuids);
            }

            foreach ($list as $key_l => $value_l) {
                $value = $value_l->toArray();

                //后台过滤掉当前登录用户
                $avatar = null; //头像
                $member_in_group_type = -1; //-1是没加入此talking
                
                if($position != 'admin'){
                    //取三个头像
                    $avatar = null;
                    $member_list = Member::where('group_id', '=', $value['group_id'])
                    ->join('group_members', 'members.uuid', '=', 'group_members.member_uuid')
                    ->select('members.avatar_url', 'members.uuid', 'group_members.type as member_in_group_type')
                    ->orderByRaw("group_members.member_uuid = '".$member_uuid. "' DESC, group_members.id ASC ")
                    ->limit(3)->get();

                    //头像合成数组
                    foreach ($member_list as $m_key => $m_value) {
                        if($m_value['uuid'] == $member_uuid){
                            $member_in_group_type = $m_value['member_in_group_type'];
                        }
                        if(!empty($m_value['avatar_url'])){
                            $avatar[] = $m_value['avatar_url'];
                        }
                    }
                }
                //人数合计
                $group_members_count = '';
                if($value['group_members_count'] > 0){
                    $group_members_count = $value['group_members_count'].'+';
                }
                $g_data = [
                    'id'=>$value['id'],//talking id
                    'uuid'=>$value['uuid'],//talking uuid
                    'group_id'=>$value['group_id'],//talking 环信 id
                    'is_top'=>$value['is_top'],//talking is_top
                    'group_icon'=> !empty($value['group_icon']) ? $value['group_icon'] :  null,//talking图标
                    'is_top_img'=> !empty($value['is_top_img']) ? $value['is_top_img'] :  null,//talking背景
                    'owner_uuid'=>$value['owner_uuid'],//talking 环信 owner_uuid
                    'title'=>$value['name'],//标题
                    'username'=>$value['create_user']['nickname'] ?? null,//创建者用户名
                    'member_uuid'=>$value['create_user']['uuid'] ?? null,//创建者uuid
                    'member_in_group_type'=>$member_in_group_type,//群创建者 type 是1
                    'avatar'=>$value['create_user']['avatar_url'] ?? null,//群创建者 头像
                    'user_list'=> //用户列表
                        [   'avatar'=>$avatar, //参与用户头像
                            'sum'=>$group_members_count,//参与用户数
                        ],
                    'online'=>$online_arr[$value['create_user']['uuid']] ?? 0,//群创建者 1在线0不在线
                    'has_like'=>LikeService::hasLike($member_uuid, 7, $value['uuid']),//1是已经点like 0是未点like
                    'sum_like'=>LikeService::sumLike(7, $value['uuid']),//300点赞
                    'created_at'=>$value['created_at'],//创建时间
                ];

                //后台
                if($position == 'admin'){
                    // 统计在线人数
                    $online_user_count = self::getGroupOnlineUserCount($value['group_id']);
                    $g_data['count_online'] = $online_user_count['count_online'];
                    $g_data['count_user'] = $value['group_members_count'];
                    //当日增消息数
                    $day = date('Ymd', time());
                    $count_message = ChatGroupMessage::where('chat_day', '=', $day)->count();
                    $g_data['count_message'] = $count_message;
                }

                $list_res[] = $g_data;
            }
        }
        $res['data'] = $list_res;
        $res['page_info'] = $res_page;

        // Cache::put($cache_key, $res, config('cache.ttl_stat'));

        return $res;
    }

    /**
     * 获取群在线用户数 
     * 
     **/
    public static function getGroupOnlineUserCount( string $group_id = ''){

        $member_list_arr = GroupMembers::where('group_id', '=', $group_id)->get()->toArray();
        //uuid提取
        $member_uuid_arr = [];
        foreach ($member_list_arr as $key => $value) {
            $member_uuid_arr[] = $value['member_uuid'];
        }
        $member_uuid_arr_chunk = array_chunk($member_uuid_arr, 100); //im一次取最大用户数 100
        
        //分批取在线用户
        $im_user_status_res_all = [];
        foreach ($member_uuid_arr_chunk as $key => $value) {
            $im_user_status_res_all += EasemobUserAuth::getUsersStatusIm($value);
        }

        $friends_online_uuid_arr = []; //在线的好uuid
        foreach ($im_user_status_res_all as $key => $value) {
            if($value == 1 ){
                $friends_online_uuid_arr[] = $key;
            }
        }
        $res['count_online'] = (int)count($friends_online_uuid_arr);
        return $res;

    }

    /**
     * 获取群成员列表 包含在线状态
     * @return array(3) {
              [0]=>
              array(13) {
                ["id"]=>
                int(1)
                ["uuid"]=>
                string(36) "1412bb19-84eb-4241-a6c2-d658b1da1203"
                ["group_id"]=>
                int(195031496458242)
                ["member_uuid"]=>
                string(36) "adad48c4-9f15-4815-a504-4f2c59687f6d"
                ["owner_uuid"]=>
                string(32) "c03b69395fa7bfeb3965b24fbae7ed56"
                ["type"]=>
                int(1)
                ["custom"]=>
                NULL
                ["sort"]=>
                int(0)
                ["chat_status"]=>
                int(0)
                ["created_at"]=>
                string(19) "2022-10-10 17:42:10"
                ["updated_at"]=>
                string(19) "1970-01-01 08:00:00"
                ["members"]=>
                array(51) {
                  ["id"]=>
                  int(3)
                  ["uuid"]=>
                  string(36) "adad48c4-9f15-4815-a504-4f2c59687f6d"
                  .........
                  .........
                  ["card_address"]=>
                  NULL
                  ["wallet_auth_state"]=>
                  int(0)
                  ["is_star"]=>
                  int(0)
                }
                ["online"]=>  
                int(0)  //用户是否在线 1在0不在
              }
     **/
    public static function getGroupMember( string $group_id = ''){

        $member_list_arr = GroupMembers::where('group_id', '=', $group_id)->get();

        //uuid提取
        foreach ($member_list_arr as $key => $value) {
            $member_uuid_arr[] = $value['member_uuid'];
        }

        $member_uuid_arr_chunk = array_chunk($member_uuid_arr, 100); //im一次取最大用户数 100
        
        //分批取在线用户
        $im_user_status_res_all = [];
        foreach ($member_uuid_arr_chunk as $key => $value) {
            $im_user_status_res_all += EasemobUserAuth::getUsersStatusIm($value);
        }

        $online_uuid_arr = []; //在线的好uuid
        foreach ($im_user_status_res_all as $key => $value) {
            if($value == 1 ){
                $online_uuid_arr[$key] = $key;
            }
        }
        $res = [];
        foreach ($member_list_arr as $key => $value) {
            $members = $value->members->toArray();
            $user = $value->toArray();
            $user['members'] = $members;
            $user['online'] = isset($online_uuid_arr[$value->member_uuid]) ? 1 : 0;

            $res[] = $user;    
        }
        return $res;
    }

    /**
     * 解散群
     * @param group_id 群id 环信id, 195031496458242 
     * @return
     **/
    public static function deleteGroup( string $group_id = ''){

        $param['group_id'] = $group_id;

        $result = Groups::destroyGroup($param);
        if (!empty($result['code'])) {
            return [ ($result['error'] ?? ''). ':' . ($result['error_description'] ?? ''), $result['code']];
        }

        //删除db 和群成员
        try {
            DB::beginTransaction();
            $gResult = Group::where('group_id', $param['group_id'])->delete();
            $mResult = GroupMembers::where('group_id', $group_id)->delete();
            DB::commit();
            return true;
        } catch (\Exception $e) {
            return (env('APP_DEBUG') ? $e->getMessage() : 'fail！');
        }
    }

    /**
     * 建群
     **/
    public static function createGroup($param = []){
        try {
            $result = Groups::createPublicGroup($param);
            if (!empty($result['code'])) {
                Log::alert(['createGroup', var_export($result, true)]);
                //return $this->failure(($result['error'] ?? '') . ':' . ($result['error_description'] ?? ''), $result['code']);
                throw new \Exception(($result['error'] ?? '') . ':' . ($result['error_description'] ?? ''), $result['code']);
            }

            $groupId = $result;
            DB::beginTransaction();
            $groupModel = new Group();
            // 保存到本地
            $groupModel->name         = $param['group_name'];
            $groupModel->group_icon   = $param['group_icon'];
            $groupModel->description  = $param['group_desc'];
            $groupModel->owner_uuid   = UtilService::memberUuidToImAccount($param['owner_uuid']);
            $groupModel->member_uuid  = $param['owner_uuid'];
            $groupModel->type         = $param['group_type'];
            $groupModel->service_type = $param['service_type'];
            $groupModel->service_uuid = $param['service_uuid'];
            $groupModel->group_id     = $groupId;
            $groupModel->public       = 1;
            $groupModel->maxusers     = env('GROUP_MAX_USER') ?? 300;
            if (!empty($param['cid'])) {
                $groupModel->cid = $param['cid'];
            }
            $groupResult = $groupModel->save();
            if (!$groupResult) {
                throw new \Exception('组保存失败', 1);
            }
            // 保存组成员
            $datas = [];
            foreach ($param['group_members'] as $member) {
                $data    = [
                    'member_uuid' => $member,
                    'owner_uuid'  => UtilService::memberUuidToImAccount($member),
                    'group_id'    => $groupId,
                    'type'        => 3,
                    'uuid'        => Str::uuid(),
                ];
                $datas[] = $data;
            }
            array_unshift($datas, [
                'member_uuid' => $param['owner_uuid'],
                'owner_uuid'  => UtilService::memberUuidToImAccount($param['owner_uuid']),
                'group_id'    => $groupId,
                'type'        => 1,
                //'uuid'        => Str::uuid()
                'uuid'        => Str::uuid()
            ]);

            GroupMembers::insert($datas);

            event(new TaskEvent(3, $param['owner_uuid']));
            DB::commit();
            return ['code' => 200, 'message' => '成功', 'res'=>$groupModel];
        } catch (\Exception $e) {
            DB::rollBack();
            return ['code' => $e->getCode(), 'message' => $e->getMessage()??'fail！'];
        }
    }

     /**
     * 查找某人在学校的群
     * @param  member_uuid
     * @return arr
     **/
    public static function findUserInSchoolGroup( string $member_uuid = '', string $school_uuid = ''){
        $data = $m_res = [];
        //查学校
        $s_res = Group::where('service_type', 'school')->where('service_uuid', $school_uuid)->first();
        
        if(!empty($s_res)){
            $s_res_arr = $s_res->toArray();
            //查成员
            $m_res = GroupMembers::where('member_uuid', $member_uuid)->where('group_id', $s_res_arr['group_id'])->first();
            if(!empty($m_res)){
                $data = $m_res;
            }
        }

        return $data;
    }

    /**
     * 某人加入学校，如果学校群不存在，就创建学校，并加入学校talking
     * @param  string member_uuid 单个用户uuid
     * @param  string school_uuid 学校uuid
     * 
     * @return ['code' => 200, 'message' => '成功'];
     **/
    public static function userSchoolTalkingCreateAndJoin( string $member_uuid = '', string $school_uuid = ''){
        $rows = School::query()
            ->where('uuid',  $school_uuid)
            ->get();
        

        if( empty($rows->toArray()) ){
            return ['code' => 199, 'message' => '没数据 '];
        }

        try {
            foreach ($rows as $row){
                // 1=未创建talking，2=已创建talking
                if($row['is_group'] == 1){
                    // 开始创建taking
                    $param['group_name'] = $row['cn_name'];
                    $param['group_icon'] = $row['school_badge_img'];
                    $param['group_desc']= $row['cn_name'];
                    $param['owner_uuid'] = env('SCHOOL_GROUP_ADMIN');
                    $param['group_type']= 4; //其它类型
                    $param['service_type']= 'school';
                    $param['service_uuid']= $row['uuid'];
                    $param['group_members'] = [];
                    $result = TalkingService::createGroup($param);
                    if(empty($result['code']) || $result['code'] != 200){
                        // throw new \Exception($result['message'], $result['code']);
                        return ['code' => $result['code'], 'message' => $result['message']??'fail！'];
                    }
                    $row->update(['is_group' => 2]);
                }

                //返回talking详情
                $g_res = Group::where('service_type', '=', 'school')->where('service_uuid', '=', $school_uuid)->first();

                //把此用户加入学校群
                if(!empty($g_res)){
                    $g_res_arr = $g_res->toArray();

                    $member_in_group = GroupMembers::where('member_uuid', '=', $member_uuid)
                        ->where('group_id', '=', $g_res_arr['group_id'])->first();
                    if(!$member_in_group){
                        $m_param['group_members'] = [$member_uuid];
                        $m_param['group_id'] = $g_res_arr['group_id'];
                        $m_param['type'] = 3;
                        $res = GroupService::addMembersGroup($m_param);
                        if($res['code'] != 200) throw new \Exception($res['message']);
                    }

                    return ['code' => 200, 'message' => '成功'];
                }else{
                    return ['code' => -201, 'message' => '学校群还没创建'];
                }
            }
        }catch (\Exception $e){
            return ['code' => $e->getCode(), 'message' => $e->getMessage()??'fail！'];
        }
    }
}